<template>
    <el-button type="primary" plain @click="open(null)"> 添加</el-button>
    <el-button type="primary" :icon="Share"> 删除</el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="productionBatch" label="生产批次" />
        <el-table-column prop="shelfLife" label="保质期(天)" />
        <el-table-column prop="licenseNumber" label="生产许可证" />
        <el-table-column prop="enterprise" label="生产企业" />
        <el-table-column prop="creator" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updator" label="修改人" />
        <el-table-column label="操作" width="400">
            <template v-slot="scope">
                <el-button type="warning" @click="open(scope.row)">修改</el-button>
                <el-button type="danger" @click="shanchu(scope.row)">删除</el-button>
                <el-button type="danger" @click="shanchu(scope.row)">导出溯源码</el-button>
                <el-button type="danger" @click="xiangqing(scope.row.productId)">详情</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <table>
        <td>
            <el-pagination v-model:current-page="cha.pageindex" v-model:page-size="cha.pagesize"
                :page-sizes="[2, 5, 7, 9]" prev-text="上一页" next-text="下一页" :background="true"
                layout="total, sizes, slot" :total="cha.totalCount" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
                <span>，共{{ cha.totalCount }}条数据，每页显示{{ cha.pageindex }}/{{ cha.totalPage }}页</span>
            </el-pagination>
        </td>
        <td>
            <el-pagination v-model:current-page="cha.pageindex" v-model:page-size="cha.pagesize"
                :page-sizes="[2, 5, 7, 9]" prev-text="上一页" next-text="下一页" :background="true"
                layout="  prev, pager, next, slot" :total="cha.totalCount" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
                <button class="btn-prev" :disabled="cha.pageindex == 1" @click="handleCurrentChange(1)">首页</button>
            </el-pagination>
        </td>
        <td>
            <el-pagination v-model:current-page="cha.pageindex" v-model:page-size="cha.pagesize"
                :page-sizes="[2, 5, 7, 9]" prev-text="上一页" next-text="下一页" :background="true" layout="slot, jumper"
                :total="cha.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                <button class="btn-prev" :disabled="cha.pageindex == cha.totalPage"
                    @click="handleCurrentChange(cha.totalPage)">尾页</button>
            </el-pagination>
        </td>
    </table>

    <!-- 添加-编辑 -->
    <el-dialog v-model="logic.isopen" :title="logic.istital" width="500" draggable>
        <el-form :model="form">
            <el-form-item label="商品名称">
                <el-input v-model="form.productName" />
            </el-form-item>
            <el-form-item label="商品批次">
                <el-input v-model="form.productionBatch" />
            </el-form-item>
            <el-form-item label="保质期(天)">
                <el-input v-model="form.shelfLife" />
            </el-form-item>
            <el-form-item label="生产许可证号">
                <el-input v-model="form.licenseNumber" />
            </el-form-item>
            <el-form-item label="生产企业">
                <el-input v-model="form.enterprise" />
            </el-form-item>
            <el-form-item label="封面图">
                <el-upload class="avatar-uploader" action="http://localhost:2972/api/PhotographPart/UploadFile"
                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="formurl" :src="formurl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="logic.isopen == false">取消</el-button>
                <el-button type="primary" @click="queding">确定 </el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script lang="ts" setup>
import { useUserStore } from '@/stores/user';
import axios from 'axios';
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const route = useRoute()
const router = useRouter()
const store = useUserStore()
const formurl = ref('')
//#region 图片
//http://localhost:2972/api/TraceabilityModule/UploadFile 
const handleAvatarSuccess = (picname: string) => {
    formurl.value = picname
    //console.log(formurl.value);//http://sortzp4b8.hb-bkt.clouddn.com/20241224185932OIP-C (1).jpg
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    ElMessage.success(rawFile.type)
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
        ElMessage.error('上传的文件格式必须是[JPG],[GIF],[PNG]格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过2MB')
        return false
    }
    return true
}
//#endregion


//#region  添加编辑
const logic = reactive({
    isopen: false,
    istital: "添加",
    isAsscess: false
})
const form = reactive({
    productId: "",//逐渐
    productName: "",//商品名称
    productionBatch: "",//生产批次
    shelfLife: "",//保质期
    licenseNumber: "",//生产许可证
    enterprise: "", //升产企业
    url: "", //封面图片

})
const open = (row: any) => {
    if (row == null) {
        logic.isopen = true
        logic.istital = "添加"
        logic.isAsscess = true
    }
    else {
        logic.isopen = true
        logic.istital = "更新"
        logic.isAsscess = false
        form.productId = row.productId
        form.productName = row.productName
        form.productionBatch = row.productionBatch
        form.shelfLife = row.shelfLife
        form.licenseNumber = row.licenseNumber
        form.enterprise = row.enterprise
        form.url = row.url
        formurl.value = form.url
        console.log(formurl.value);
    }
}
const queding = () => {
    if (logic.isAsscess) {
        form.url = formurl.value;
        axios.post("http://localhost:2972/api/TraceabilityModule/CreateCompany", form)
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加成功")
                    logic.isopen = false
                    xianshi()
                } else {
                    ElMessage.error("添加失败")
                }
            })
    } else {
        axios.post("http://localhost:2972/api/TraceabilityModule/UPdateCompany", form)
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("更新成功")
                    logic.isopen = false
                    xianshi()
                } else {
                    ElMessage.error("更新失败")
                }
            })
    }
}

//#endregion

//#region  删除
const shanchu = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("http://localhost:2972/api/TraceabilityModule/DelecteCompany", row)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success("删除成功")
                        logic.isopen = false
                        xianshi()
                    } else {
                        ElMessage.error("删除失败")
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}
//#endregion


//#region  分页
const tableData = ref([])
const cha = reactive({
    pageindex: 1,
    pagesize: 5,
    totalCount: "",
    totalPage: "",
})
const xianshi = () => {
    axios.get("http://localhost:18675/api/TraceabilityCreadePart/GetLogin", {
        params: {
            pageindex: cha.pageindex,
            pagesize: cha.pagesize,
        }
    })
        .then(res => {
            tableData.value = res.data.data.data

            cha.totalCount = res.data.data.totalCount
            cha.totalPage = res.data.data.totalPage
        })
}
const handleSizeChange = (val: any) => {
    cha.pagesize = val;
    xianshi()
}
const handleCurrentChange = (val: any) => {
    cha.pageindex = val;
    xianshi()
}
onMounted(() => {
    xianshi()
})
//#endregion

// //详情  
const xiangqing = (productId: number) => {
    // 使用 Vue Router 跳转并传递 ID 参数
    router.push("/Detail?productId=" + productId)
    console.log(productId);

}

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>